﻿using CommonTools;
using shop.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace shop.Web.Common
{
    public class UserHelper
    {
        /// <summary> 登录 </summary>
        public async Task<JUser> TryLogin(string name, string pwd)
        {
            string pwdMd5 = MD5.MD5code(pwd);

            var u = await DB.FSql.Select<JUser>()
                .Where(a => a.Isdel == false && a.Name == name)
                .ToOneAsync();

            if (u == null)
            {
                //日志
                DB.FSql.Insert(new CLogs()
                {
                    DocId = "",
                    DocAction = "登录",
                    DocName = "JUser",
                    Note = "登录失败, 没有用户名:" +name,
                    Zdr = name,
                }).ExecuteAffrows();

                return new JUser();
            }
            else if ((string.IsNullOrEmpty(u.Password.Trim()) && string.IsNullOrEmpty(pwdMd5))
                     || (string.Equals(pwdMd5, u.Password, StringComparison.OrdinalIgnoreCase)))
            {
                //检查密码: 密码可以同时是空,null,  MD5不区分大小写
                //密码正确

                //日志
                DB.FSql.Insert(new CLogs()
                {
                    DocId = "",
                    DocAction = "登录",
                    DocName = "JUser",
                    Note = "登录, 用户名:" + name,
                    Zdr = name,
                }).ExecuteAffrows();

                return u;
            }
            else
            {
                //日志
                DB.FSql.Insert(new CLogs()
                {
                    DocId = "",
                    DocAction = "登录",
                    DocName = "JUser",
                    Note = "登录, 用户名:" + name+ ", 密码错误",
                    Zdr= name
                }).ExecuteAffrows();

                return new JUser();
            }
        }
    }
}
